package com.yue.ssa.controller;

import com.yue.ssa.bean.RespBean;
import com.yue.ssa.bean.User;
import com.yue.ssa.common.Constant;
import com.yue.ssa.common.VerificationCode;
import com.yue.ssa.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Api(value = "免登录接口", tags = "免登录接口")
@RestController
@RequestMapping("rest/open")
public class OpenController {

    @Autowired
    JavaMailSender javaMailSender;
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Value("${spring.mail.username}")
    private String account;

    Logger logger = LoggerFactory.getLogger(OpenController.class);

    @ApiOperation(value = "获取验证码", notes = "获取验证码")
    @GetMapping("verifyCode")
    public void verifyCode(HttpSession session, HttpServletResponse resp) throws IOException {
        VerificationCode code = new VerificationCode();
        BufferedImage image = code.getImage();
        String text = code.getText();
        session.setAttribute("verify_code", text);
        VerificationCode.output(image, resp.getOutputStream());
    }

    @ApiOperation(value = "发送邮箱", notes = "发送邮箱")
    @GetMapping("sendEmail")
    public RespBean sendEmail(String email) {
        if (StringUtils.isBlank(email)) return RespBean.error(Constant.EMAIL_FORMAT_ERROR);
        String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern regex = Pattern.compile(check);
        Matcher matcher = regex.matcher(email);
        if (!matcher.matches()) {
            return RespBean.error(Constant.EMAIL_FORMAT_ERROR);
        }
        User user = userService.getByEmail(email);
        if (user == null) {
            return RespBean.error(Constant.EMAIL_NOTEXIST);
        }
        String str = "0123456789";
        StringBuilder sb = new StringBuilder(6);
        for (int i = 0; i < 6; i++) {
            char ch = str.charAt(new Random().nextInt(str.length()));
            sb.append(ch);
        }
        try {
            //1.构建一个邮件对象
            SimpleMailMessage message = new SimpleMailMessage();
            //2.设置邮件主题
            message.setSubject("【大帅集团】：请查收您的验证码");
            //3.设置邮件发送者
            message.setFrom(account);
            //4. 设置邮件接收者，可以有多个接收者
            message.setTo(email);
            //7.设置邮件发送日期
            message.setSentDate(new Date());
            //8. 设置邮件的正文
            message.setText(Constant.EMAIL_VERIFY_MSG.replace("{code}", sb.toString()));
            //9. 发送邮件
            javaMailSender.send(message);
            logger.info("已向邮箱为" + email + "的用户发送验证码：" + sb.toString());
            //验证码保存在redis 5分钟过期
            redisTemplate.opsForValue().set(email, sb.toString(), 5, TimeUnit.MINUTES);
            return RespBean.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return RespBean.error(e.getMessage());
        }
    }
}
